<template>
  <div>
    <van-search
      v-model.trim="value"
      shape="round"
      @input="onsearch"
      placeholder="请输入搜索关键词"
    />
    <div v-if="!value" class="hot">
      <p>热门搜索</p>
      <span
        @click="goseach(item.first)"
        v-for="(item, index) in hots"
        :key="index"
        >{{ item.first }}</span
      >
    </div>
    <div v-else>
      <van-cell title="最佳匹配" />
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="iserror"
        :immediate-check="false"
        error-text="网络开小差了"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <music-item :item="item" v-for="item in list" :key="item.id" />
      </van-list>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getflag, searchSong } from '@/api/search.js'
import MusicItem from '../../components/MusicItem.vue'
export default {
  components: { MusicItem },
  name: 'SEARCH',
  data () {
    return {
      value: '',
      hots: [],
      list: [],
      loading: false,
      finished: false,
      iserror: false,
      page: 1,
      limit: 20,
      count: 0
    }
  },

  created () {
    this.getFlag()
  },
  methods: {
    goseach (i) {
      this.value = i
      this.onsearch()
    },
    async getFlag () {
      try {
        const res = await getflag()
        this.hots = res.data.result.hots
      } catch (err) {
        Toast.fail(err.messages)
      }
    },
    onsearch () {
      this.list = []
      this.page = 1
      this.finished = false
      this.loading = true
      clearTimeout(this.ids)
      if (!this.value) return
      this.ids = setTimeout(() => {
        this.onLoad()
      }, 700)
    },
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // 请求数据
      try {
        const res = await searchSong({
          keywords: this.value,
          limit: this.limit,
          offset: (this.page - 1) * this.limit
        })
        if (res.data.result.songs) {
          this.list.push(...res.data.result.songs)
          this.page++
          this.count = res.data.result.songCount
        } else {
          this.count = 0
        }
        // 保存数据
        // this.list = res.data.result.songs
      } catch (err) {
        this.iserror = true
        Toast.fail(err.messages)
      }
      // 加载状态结束
      this.loading = false
      // 数据全部加载完成
      if (this.list.length >= this.count) this.finished = true
    }
  }
}
</script>

<style scoped lang="less">
.hot {
  padding: 10px 10px;
  p {
    color: #ccc;
    padding: 5px 10px;
  }
  span {
    margin: 2px 4px;
    padding: 5px 10px;
    font-size: 12px;
    display: inline-block;
    border: 1px solid #c20c0c;
    border-radius: 20px;
  }
}
</style>
